package com.offcn.user.controller;

import com.github.pagehelper.PageInfo;
import com.offcn.bean.ConditionBean;
import com.offcn.bean.Moviedetailtable;
import com.offcn.bean.Movietable;
import com.offcn.movie.service.CategroyService;
import com.offcn.movie.service.MovieService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("movie")
public class MovieController {

    @Resource
    private MovieService movieService;
    @Resource
    private CategroyService categroyService;

    //进入新增页面
    @RequestMapping("show-add-movie")
    public String showAddMovie(){
        return "/WEB-INF/jsp/movie/movieadd.jsp";
    }

    //实现新增功能
    @RequestMapping("add-movie")
    public String AddMovie(Movietable movietable, Moviedetailtable moviedetailtable, MultipartFile files, HttpServletRequest request) throws IOException {
        movietable.setStatus(1);
        movietable.setSource("iqiyi");
        if(files != null){
            String oldName = files.getOriginalFilename();
            int index = oldName.lastIndexOf(".");
            String extName = "";
            if(index != -1)
                extName = oldName.substring(index);
            String newName = UUID.randomUUID().toString().replaceAll("-","") + extName;
            String path = request.getSession().getServletContext().getRealPath("photo");
            File file = new File(path,newName);
            files.transferTo(file);

            movietable.setSaveimagepath("/photo/"+newName);
        }

        movieService.save(movietable,moviedetailtable);
        return "redirect:/movie/show-movie";
    }


    @RequestMapping("show-movie")
    public String showMovie(@RequestParam(defaultValue = "1") int currentPage, ConditionBean conditionBean, Model model){
        conditionBean.setFromS("back");
        //送回搜索条件
        List<String> searchS = categroyService.queryCategroyNameList();
        List<String> searchS1 = new ArrayList<>();
        searchS1.add("所有类型");
        searchS1.addAll(searchS);
        searchS1.add("电影名称");
        //分页数据
        PageInfo<Movietable> pageInfo = movieService.queryMovieList1(9,currentPage,conditionBean);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("searchS",searchS1);
        model.addAttribute("conditionBean",conditionBean);
        return "/WEB-INF/jsp/movie/movielist.jsp";
    }
}
